package com.feiyue.learning.advance.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * 读取客户端的输入，回显到客户端
 * @author  feiyue
 * @date  2020/4/19
 */
public class ReactorServer implements Runnable {
    Selector selector;
    ServerSocketChannel serverSocketChannel;

    // Reactor 初始
    public ReactorServer() throws IOException {
        selector = Selector.open();

        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress(80));
        SelectionKey sk = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 新建连接处理器，作为附件，绑定到 sk 选择键
        sk.attach(new AcceptorHandler());
        System.out.println("Reactor Server init&attach success");
    }

    @Override
    public void run() {
        try {
            while(!Thread.interrupted()) {
                selector.select();
                Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                while (keyIterator.hasNext()) {
                    // 反应器负责 dispatch 收到的事件
                    SelectionKey key = keyIterator.next();
                    dispatch(key);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dispatch(SelectionKey key) {
        Runnable handle = (Runnable) key.attachment();
        if (handle != null) {
            handle.run();
        }
    }

    class AcceptorHandler implements Runnable {

        @Override
        public void run() {
            try {
                SocketChannel channel = serverSocketChannel.accept();
                if (channel != null) {
                    new EchoHandler(selector, channel);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new Thread(new ReactorServer()).start();
    }
}
